package com.splic.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.splic.common.utils.uuid.IdUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

@Slf4j
public class OssUtils {

    public static final String endpoint = "oss-cn-beijing.aliyuncs.com";
//    public static final String accessKeyId = "LTAI5tPkYW3G12RtpfSUFazU";
    public static final String accessKeyId = "LTAI5tGruFKEsFU7LPxLzeq4";
//    public static final String accessKeySecret = "T7BaSALBmxD9Dg4M9u0kCgzIUG6h5X";
    public static final String accessKeySecret = "MDCuwVGUS99q3Chay91VN4jJGxPZwz";
    public static final String bucketName = "easyjoy";
    public static final String accessHost = "https://easyjoy.oss-cn-beijing.aliyuncs.com";

    public static OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    public static void main(String[] args) throws Exception {
        String folderName = "product/upload/2022/04/07/"+ IdUtils.fastUUID() + ".jpg";
        String path = "C:\\Users\\EDZ\\Desktop\\验证邮箱html2.3\\验证邮箱html2.3\\html-重置密码\\闹钟-重置密码\\椭圆2.png";
        String url = uploadFile(folderName, new File(path));

        //InputStream inputStream = new URL("http://121.5.4.197:8099/upload/2022/03/31/af5c7a8f-4a6a-4acc-82df-2c46eaa63a61.png").openStream();
        //String url = uploadFile(folderName, inputStream);
        System.out.println("上传文件完成。url:"+url);
    }

    /**
     * 上传文件
     * @param filePath   上传文件路径
     * @param file       待上传文件
     * @return
     * @throws Exception
     */
    public static String uploadFile(String filePath, File file) {
       try {
           ossClient.putObject(bucketName, filePath,file);
           return accessHost +"/"+ filePath;
       }catch (Exception e){
           log.error("文件上传oss失败");
           return "";
       }finally {
           //ossClient.shutdown();
       }
    }

    /**
     * 上传文件
     * @param filePath   上传文件路径
     * @param inputStream       待上传文件
     * @return
     * @throws Exception
     */
    public static String uploadFile(String filePath, InputStream inputStream) {
        try {
            ossClient.putObject(bucketName, filePath,inputStream);
            return accessHost +"/"+ filePath;
        }catch (Exception e){
            log.error("文件上传oss失败");
            return "";
        }finally {
            //ossClient.shutdown();
        }
    }
}
